import dgram from 'dgram'
import EventEmitter from 'events'
class UdpService extends EventEmitter {
  constructor() {
    super()
    this.client = dgram.createSocket('udp4')
    this.isConnected = false
    this.initializeClient()
  }
  static getInstance() {
    if (!UdpService.instance) {
      UdpService.instance = new UdpService()
    }
    return UdpService.instance
  }
  initializeClient() {
    this.client.on('error', (error) => {
      console.error('UDP 错误:', error)
      this.emit('error', error)
    })
    this.client.on('message', (msg, rinfo) => {
      try {
        const message = msg.toString('utf-8')
        console.log('收到udp消息:', message)
        this.emit('udp-message', {
          from: rinfo,
          message: message
        })
      } catch (error) {
        console.error('UDP消息处理错误:', error)
      }
    })
    this.client.on('connect', () => {
      this.isConnected = true
      this.emit('connected')
    })
    this.client.on('close', () => {
      this.isConnected = false
      this.emit('closed')
    })
  }
  async sendMessage({ message, port, host }) {
    return new Promise((resolve, reject) => {
      const buffer = Buffer.isBuffer(message) ? message : Buffer.from(message)
      this.client.send(buffer, port, host, (error) => {
        if (error) {
          console.error('UDP 发送失败:', error)
          reject(error)
          return
        }
        console.log('UDP 发送成功')
        resolve(true)
      })
    })
  }
  close() {
    if (this.isConnected) {
      this.client.close()
    }
  }
}

export default UdpService 